﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using StudyStationWEBAPI.Model;
using StudyStationWEBAPI.Models;

namespace StudyStationWEBAPI.Controllers
{
    /// <summary>
    /// 用户的注册，登录，修改信息
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private Encription encription = new Encription();
        //注入MySQL DataBase
        private StationContext db;
        public UserController(StationContext context)
        {
            this.db = context;
        }
        //返回所有用户的信息 Get:api/user
        [HttpGet] 
        public IQueryable<User> GetUsers()
        {
            return db.Users;
        }
        //注册用户 Post:api/user/register
        [HttpPost("Register")]
        public IActionResult Postuser(User user)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            try
            {
                //判断是否有同用户名的用户
                var tmp = db.Users.SingleOrDefault(x => x.name == user.name);
                if(tmp != null)
                {
                    return BadRequest("用户已存在");
                }
                else
                {
                    user.password = encription.GetMD5Hash(user.password);
                    db.Users.Add(user);
                    db.SaveChanges();
                    return Ok(user);
                }
            }
            catch (Exception dbEx)
            {
                Console.WriteLine(dbEx.Message);
                return BadRequest();
            }
        }
        //登录用户 Get:api/user/login
        [HttpGet("Login")]
        public IActionResult Login(string name,string pwd)
        {
            try
            {
                pwd = encription.GetMD5Hash(pwd);//进行MD5码的转换
                User user = db.Users.FirstOrDefault(x => x.name == name);//查询用户
                if(user==null)
                {
                    return BadRequest("用户不存在");
                }
                if(user.password!=pwd)
                {
                    return BadRequest("密码错误");
                }
                //成功查询到用户之后返回唯一的Token表示
                string Token = encription.GetToekn(name);
                if(Token != null)
                {
                    user.token = Token;
                    db.SaveChanges();
                }
                return Ok(Token); // 登陆成功，返回唯一标识用户的token
            }
            catch
            {
                return BadRequest();
            }
        }
    }
}
